//头部

import React from "react";
import { message } from "antd";
import "./adminheader.less";
import { Redirect, withRouter } from "react-router-dom";
import { getWeather } from "../../api/index";

import menuList from "../../config/menuConfig";

// 后台管理的home页
class AdminHeader extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      datauser: null,
      weatherobj: null,
      time1: "",
      title: "首页",
    };
  }

  componentWillMount() {
    let userdata = JSON.parse(sessionStorage.getItem("userdata"));
    if (userdata) {
      this.setState({
        userdata,
      });
    }

    //获取当前天气
    getWeather().then((data) => {
      this.setState({
        weatherobj: data.data.now,
      });
    });

    //获取当前时间
    setInterval(this.newTime, 1000);
  }

  componentDidMount() {
    let url = this.props.location.pathname;
    let title = this.getTitle(url);
    if (title) {
      this.setState({
        title,
      });
    }
  }

  // 动态获取当前的title
  getTitle = (url) => {
    let title = "首页";
    menuList.find((item) => {
      if (!item.children) {
        if (item.key === url) {
          title = item.title;
        }
      } else {
        item.children.find(item1 => {
          if (item1.key === url) {
            title = item1.title;
          }
        });
      }
    });

    return title;
  };

  // 退出登陆
  outLogin = () => {
    sessionStorage.removeItem("userdata");

    this.props.history.replace("/login");
    message.success("退出成功");
  };

  // 计时器

  newTime = () => {
    let time = new Date().toLocaleTimeString();
    this.setState({
      time1: time,
    });
  };

  render() {
    return (
      <div className="admin-header-top">
        <div className="top-right">
          欢迎
          {this.state.userdata != null
            ? this.state.userdata.username
            : "没有登陆"}
          ,<button onClick={this.outLogin}>退出</button>
        </div>
        <div className="admin-header-footer">
          <div className="left">
            <h3>{this.state.title}</h3>
          </div>
          <div className="right">
            <span>
              {this.state.time1
                ? this.state.time1
                : new Date().toLocaleTimeString()}
            </span>
            <span>
              {this.state.weatherobj != null ? this.state.weatherobj.text : ""}
              &nbsp; 当前温度:&nbsp;
              {this.state.weatherobj != null ? this.state.weatherobj.temp : ""}℃
            </span>
          </div>
        </div>
      </div>
    );
  }
}

export default withRouter(AdminHeader);
